/*
 *    Copyright (c) 2018-2025, shenghua All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: shenghua
 */

package com.chen.base.module.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.chen.base.module.excel.exception.ExcelMaxTotalRowsException;
import com.chen.base.module.excel.handler.ExcelDataHandle;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 陈锦龙
 * @since 2022/7/18 9:33
 */
@Slf4j
public class ExcelListener<T> extends AnalysisEventListener<T> {
	/** 缓存的数据集 */
	private final List<T> list = new ArrayList<>();
	/** 数据处理者 */
	private final ExcelDataHandle<T> handle;
	/** 总行数 */
	private int totalRow = 0;
	/** 当前页 */
	private int curr = 1;

	public ExcelListener(ExcelDataHandle<T> handle){
		this.handle = handle;
	}

	@SneakyThrows
	@Override
	public void invoke(T data, AnalysisContext context) {
		if (totalRow == 0){
			totalRow = context.readSheetHolder().getApproximateTotalRowNumber();
			log.info("excel总行数：{}",totalRow);
			if (handle.maxTotalRows() != -1 && totalRow > handle.maxTotalRows()){
				throw new ExcelMaxTotalRowsException("总行数超过最大值！总行数限制：" + handle.maxTotalRows() + "条");
			}
		}

		list.add(data);
		if (list.size() >= handle.getBatchCount()){
			submit();
			++curr;
		}
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext context) {
		submit();
	}

	/**
	 * 提交批数据到ExcelDataHandle中
	 */
	private void submit(){
		log.info("excel数据：{}页", curr);
		// 数据处理
		handle.dataHandler(new ArrayList<>(list), totalRow);
		// 清除缓存的数据，方便GC回收
		list.clear();
	}

}
